package org.papervision3d.core.controller
{
	import flash.utils.getTimer;
	
	import org.papervision3d.core.animation.track.AbstractTrack;
	import org.papervision3d.core.geom.TriangleMesh3D;
	
	/**
	 * @author Tim Knip
	 */ 
	public class AnimationController implements IObjectController
	{
		public static const STATE_STOPPED :int = 0;
		public static const STATE_PLAYING :int = 1;
		public static const STATE_PAUSED :int = 2;
		
		/**
		 * 
		 */ 
		public function get state():int
		{
			return _state;	
		}
		
		private var _last :int;
		private var _tracks :Array;
		private var _startTime :Number;
		private var _endTime :Number;
		private var _state :int;
		private var _pauseInterval :int;
		
		/**
		 * 
		 */ 
		public function AnimationController()
		{
			_last = getTimer();
			_tracks = new Array();
			_startTime = Number.MAX_VALUE;
			_endTime = -_startTime;
			_state = STATE_STOPPED;
			_pauseInterval = 0;
		}
		
		/**
		 * 
		 */ 
		public function addTrack(track:AbstractTrack):AbstractTrack
		{
			if(_tracks.indexOf(track) == -1)
			{
				_tracks.push(track);	
				_startTime = Math.min(_startTime, track.startTime);
				_endTime = Math.max(_endTime, track.endTime);
			}
			return track;
		}
		
		/**
		 * 
		 */ 
		public function pause():void
		{
			_pauseInterval = getTimer() - _last;
			_state = STATE_PAUSED;
		}
		
		/**
		 * Resumes the animation. 
		 */ 
		public function resume():void
		{
			_last = getTimer() - _pauseInterval;	
			_state = STATE_PLAYING;
		}
		
		/**
		 * Start the animation. 
		 */ 
		public function start():void
		{
			_last = getTimer();	
			_state = STATE_PLAYING;
		}
		
		/**
		 * Stop the animation
		 */ 
		public function stop():void
		{
			_state = STATE_STOPPED;
		}
		
		/**
		 * 
		 */ 
		public function update():void
		{
			if(_state != STATE_PLAYING || !_tracks || !_tracks.length) return;
			
			var track :AbstractTrack;
			var currentTime :int = getTimer();
			var elapsed :Number = (currentTime - _last) * 0.001;
			
			if(elapsed >= (_endTime - _startTime))
			{
				_last = currentTime;
				elapsed = _startTime;
			}

			for each(track in _tracks)
			{
				track.tick(elapsed);
			}
		}	
	}
}